/*
* 工位设备管理模块
*/
const express = require('express');
const router = express.Router();
// 引入数据库
const db = require("../../../config/db");
// 引入时间包
const moment = require("moment");
// 引入方法库
const { toCamelCase, toUnderlineCase, verifyToken} = require("../../../config/utils");
// 引入日志
const log = require("../../log");

// 获取所有工位设备列表
router.get("/list", async (req, res) => {
    console.log("===========获取工位设备列表接口============");
    // 获取参数
    let { pageNum, pageSize, workstationId } = req.query;
    // 拼接sql语句
    let sql = "select * from md_workstation_machine";
    let sql_where = ` where 1=1`;
    if(workstationId){
        sql_where += ` and workstation_id like '%${workstationId}%'`;
    }
    if(workstationId){
        sql += sql_where;
    }
    
    // 分页
    sql += ` limit ${(pageNum-1)*pageSize}, ${pageSize}`;
    // 查询数据库
    db.query("查询工位设备列表", sql, (err, result)=>{
        if(err){
            res.send({code: 500, msg: "查询工位设备列表失败", data: err});
            return;
        }
        // 查询总数
        db.query("查询工位设备总数", `select count(*) as count from md_workstation_machine ${sql_where}`, (err, count)=>{
            if(err){
                res.send({code: 500, msg: "查询工位设备总数失败", data: err});
                return;
            }
            if(result.length > 0){
                 // 变量Json数组key转成下划线第一个大写
                 result = result.map(item => {
                    return toCamelCase(item)
                })
                res.send({code: 200, msg: "查询工位设备列表成功", rows: result, total: count[0].count});
            }else{
                res.send({code: 200, msg: "查询工位设备列表成功", rows: [], total: 0});
            }
        })
    })
})

// 添加工位设备
router.post("/", async (req, res) => {
    console.log("===========添加工位设备接口============");
    // 获取参数
    let { workstationId, machineryId, machineryName, machineryCode } = req.body;
     // 获取创建人
     let {username} = verifyToken(req.headers.authorization);
     // 获取创建时间
     let createTime = moment().format("YYYY-MM-DD HH:mm:ss");
     // 判断设备是否添加到工位上
     db.query("查询设备是否添加到工位上", `select * from md_workstation_machine where machinery_id = '${machineryId}'`, (err, result)=>{
        if(err){
            res.send({code: 500, msg: "查询设备是否添加到工位上失败", data: err});
            return;
        }
        if(result.length > 0){
            // 查询工位名称
            db.query("查询工位名称", `select workstation_name from md_workstation where workstation_id = '${workstationId}'`, (err, workstation_name_result)=>{
                if(err){
                    res.send({code: 500, msg: "查询工位名称失败", data: err});
                    return;
                }
                res.send({code: 500, msg: `设备[ ${machineryName} ]已分配至工作站：[ ${workstation_name_result[0].workstation_name} ]上`});
            })
            return;
        }
        // 插入数据库
        let sql = `insert into md_workstation_machine ( workstation_id, machinery_id, machinery_name, machinery_code, quantity, create_by, create_time ) 
        values
        ('${workstationId}', '${machineryId}', '${machineryName}', '${machineryCode}', '1', '${username}', '${createTime}')`;
        db.query("添加工位设备", sql, (err, result)=>{
            if(err){
                res.send({code: 500, msg: "添加工位设备失败", data: err});
                return;
            }
            if(result.affectedRows > 0){
                res.send({code: 200, msg: "添加工位设备成功", data: []});
            }else{
                res.send({code: 500, msg: "添加工位设备失败", data: []});
            }
        })
     })
})

// 删除工位设备
router.delete("/:id", (req, res) => {
    console.log("===========删除工位设备接口============");
    // 获取参数
    let {id} = req.params;
     // 拼接sql,删除多条数据
     let sql = `delete from md_workstation_machine where record_id in(${id})`;
    // 查询数据库
    db.query("删除工位设备", sql, (err, result) => {
        if (err) {
            res.send({code: 500, msg: "删除工位设备失败", data: err});
            return
        }
        if(result.affectedRows > 0){
            res.send({code: 200, msg: "删除工位设备成功"})
        }else{
            res.send({code: 500, msg: "删除工位设备失败"})
        }
    })
})


module.exports = router;
